/**
 * 
 */
package sailing.io.file;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import javax.swing.JComponent;
import javax.swing.JFileChooser;

import org.jdesktop.application.SingleFrameApplication;

import sailing.app.SailingApplication;
import sailing.excel.ExcelParseFactory;
import sailing.excel.ExcelParser;
import sailing.ui.progressdialog.ProgressDialog;
import sailing.worker.FileLoadWorker;
import cjlite.logger.Logger;
import cjlite.utils.Lists;

/**
 * @author kevin
 * 
 */
public class ExcelFiles {
	private static Logger logger = Logger.thisClass();

	private static SingleFrameApplication app = SailingApplication.getAppInstance();

	public static String getImportFile(JComponent componenet) {
		String path = null;
		JFileChooser fc = new JFileChooser();
		fc.setFileFilter(new ExcelFileFilter());
		fc.setDialogTitle("请选择要导入的文件...");
		fc.setApproveButtonText("确定");
		fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
		if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(componenet)) {
			path = fc.getSelectedFile().getPath();
		}
		logger.trace("file path='{0}'", path);
		return path;
	}

	public static <T> List<T> loadData(String title, JComponent componenet, String path, Class<T> clazz) {
		CountDownLatch cdl = new CountDownLatch(1);
		try {
			ExcelParser ep = ExcelParseFactory.get(clazz);
			FileLoadWorker flw = new FileLoadWorker(path, ep);
			ProgressDialog pd = ProgressDialog.loadDialog(title, componenet, app);

			pd.setFileWorker(flw);
			pd.setVisible(true);
			flw.await();
			logger.trace("import action end........");
			return ep.getParsedDataList();
		} catch (Exception e1) {
			logger.trace("error on load data{0}", e1, path);
		}

		return Lists.newArrayList();
	}

}
